<!-- eslint-disable vue/no-unused-vars -->
<!-- eslint-disable vue/require-v-for-key -->
<template>
  <div class="index-page">
    <div v-if="showAnnouncement" class="announcement">
      <div class="scrolling-text">
        <span>
          <SoundFilled />
          {{ announcementMessage }}
        </span>
      </div>
    </div>
    <div
      class="logo"
      style="display: flex; justify-content: center; margin-bottom: 20px"
    >
      <img src="../assets/聚合搜索Logo.png" alt="Logo" style="height: 150px" />
    </div>
    <a-input-group style="width: 1000px">
      <a-input-search
        v-model:value="searchText"
        placeholder="请输入搜索关键词"
        enter-button="搜索"
        size="large"
        @search="onSearch"
        style="width: 800px"
      />
      <a-button
        type="primary"
        @click="showModal"
        style="width: 130px; height: 40px"
        >请求添加数据源</a-button
      >
    </a-input-group>

    <a-modal
      @cancel="handleCancel"
      title="请求添加数据源"
      :visible="isModalVisible"
    >
      <a-form :form="form" layout="horizontal" v-bind="formItemLayout">
        <a-form-item label="标题名称" name="title">
          <a-input v-model:value="form.title" />
        </a-form-item>
        <a-form-item label="描述" name="description">
          <a-textarea :rows="3" v-model:value="form.description" />
        </a-form-item>
        <a-form-item label="类型" name="type">
          <a-select v-model:value="form.type" placeholder="选择类型">
            <a-select-option value="1">链接</a-select-option>
            <a-select-option value="2">文章</a-select-option>
            <a-select-option value="3">图片</a-select-option>
            <a-select-option value="4">视频</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="作者名称" name="authorName">
          <a-input v-model:value="form.authorName" />
        </a-form-item>
        <a-form-item label="作者邮箱" name="authorEmail">
          <a-input v-model:value="form.authorEmail" />
        </a-form-item>
      </a-form>
      <a-row>
        <a-col :span="10">
          <a-upload
            v-model:file-list="codefileList"
            :max-count="1"
            :headers="headers"
            action="http://localhost:8101/api/file/upload"
            @change="handleCodeChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              <a-icon type="upload" />
              导入数据源代码
            </a-button>
          </a-upload>
        </a-col>
        <a-col :span="10" :offset="2">
          <a-upload
            v-model:file-list="docfileList"
            :max-count="1"
            :headers="headers"
            action="http://localhost:8101/api/file/upload"
            @change="handleDocChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              <a-icon type="upload" />
              导入说明文档
            </a-button>
          </a-upload>
        </a-col>
      </a-row>
      <template #footer>
        <div>
          <a-button @click="handleCancel">取消</a-button>
          <a-button v-if="!isLoading" type="primary" @click="handleOk"
            >提交</a-button
          >
          <a-button v-else type="primary" loading>加载中</a-button>
        </div>
      </template>
    </a-modal>
    <MyDivider />
    <a-tabs v-model:activeKey="activeKey" @change="onTabChange">
      <a-tab-pane v-if="hasItem('post')" key="post" tab="文章">
        <div class="isGetData" v-if="!isGetData">
          <a-spin />
        </div>
        <PostList v-else :post-list="myDataList.postDataSource" />
      </a-tab-pane>
      <a-tab-pane v-if="hasItem('picture')" key="picture" tab="图片">
        <div class="isGetData" v-if="!isGetData">
          <a-spin />
        </div>
        <PictureList v-else :picture-list="myDataList.pictureDataSource" />
      </a-tab-pane>
      <a-tab-pane v-if="hasItem('user')" key="user" tab="用户">
        <div class="isGetData" v-if="!isGetData">
          <a-spin />
        </div>
        <UserList v-eles :user-list="myDataList.userDataSource" />
      </a-tab-pane>
      <a-tab-pane v-if="hasItem('video')" key="video" tab="视频">
        <div class="isGetData" v-if="!isGetData">
          <a-spin />
        </div>
        <VideoList v-else :video-list="myDataList.videoDataSource"></VideoList>
      </a-tab-pane>
    </a-tabs>
    <div
      v-if="isGetData && initLoading"
      :style="{
        textAlign: 'center',
        marginTop: '12px',
        height: '48px',
        lineHeight: '64px',
      }"
    >
      <a-button @click="onLoadMore">加载更多</a-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onActivated,
  ref,
  watchEffect,
  onMounted,
  reactive,
  toRefs,
  watch,
  computed,
} from "vue";
import PostList from "@/components/PostList.vue";
import PictureList from "@/components/PictureList.vue";
import UserList from "@/components/UserList.vue";
import MyDivider from "@/components/MyDivider.vue";
import { useRoute, useRouter } from "vue-router";
import myAxios from "@/plugins/myAxios";
import { UploadChangeParam, message } from "ant-design-vue";
import VideoList from "@/components/VideoList.vue";

const myDataList = ref({
  pictureDataSource: [],
  postDataSource: [],
  userDataSource: [],
  videoDataSource: [],
});

const route = useRoute();
const router = useRouter();
const activeKey = route.params.category;

const initSearchParams = {
  type: activeKey,
  text: "",
  pageSize: 20,
  current: 1,
};
//点击“请求添加数据源”弹出表单
const isModalVisible = ref(false);
const form = reactive({
  title: "",
  type: "1",
  authorEmail: "",
  authorName: "",
  codeUrl: "",
  description: "",
  documentUrl: "",
});
const showModal = () => {
  isModalVisible.value = true;
};
const isLoading = ref(false);
const handleOk = () => {
  console.log(form);
  isLoading.value = true;
  //调接口提交
  myAxios
    .post("/feign/datasource/application/commit", form)
    .then((res: any) => {
      if (res !== "") {
        message.success(res);
        isModalVisible.value = false;
      }
      isLoading.value = false;
    });
};

const formItemLayout = computed(() => {
  return {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
  };
});

const handleCancel = () => {
  isModalVisible.value = false;
};
const isGetData = ref(false);
const initLoading = ref(false);
const verifyLoading = (type: string) => {
  if (!isGetData.value) {
    return false;
  }
  //拿到关键词
  const code = type;
  const len = ref(0);
  console.log("加载更多的code" + code);
  if (code === "post") {
    len.value = myDataList.value.postDataSource
      ? myDataList.value.postDataSource.length
      : 0;
  } else if (code === "picture") {
    len.value = myDataList.value.pictureDataSource
      ? myDataList.value.pictureDataSource.length
      : 0;
  } else if (code === "video") {
    len.value = myDataList.value.videoDataSource
      ? myDataList.value.videoDataSource.length
      : 0;
  } else if (code === "user") {
    len.value = myDataList.value.userDataSource
      ? myDataList.value.userDataSource.length
      : 0;
  }
  console.log("长度：" + len.value);
  if (len.value >= 20) {
    //则需要展示
    return true;
  } else {
    return false;
  }
};
const refCurrent = ref(1);

const onLoadMore = () => {
  searchParams.current += 1;
  refCurrent.value = searchParams.current;
  console.log("加载更多");
  console.log(refCurrent);
  console.log(searchParams);
};

const searchText = ref(route.query.text || "");

//文件上传
const codefileList = ref([]);
const docfileList = ref([]);
const codeFileUrl = ref();
const docFileUrl = ref();
const headers = {
  authorization: "authorization-text",
};
const handleCodeChange = (info: UploadChangeParam) => {
  if (info.file.status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === "done") {
    if (info.file.response.code !== 0) {
      message.error(`${info.file.name} 文件上传失败！`);
      return;
    }
    codeFileUrl.value = info.file.response.data;
    form.codeUrl = codeFileUrl.value;
    message.success(`${info.file.name} 文件上传成功！`);
  } else if (info.file.status === "error") {
    message.error(`${info.file.name} 文件上传失败！`);
  }
};

const handleDocChange = (info: UploadChangeParam) => {
  if (info.file.status !== "uploading") {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === "done") {
    if (info.file.response.code !== 0) {
      message.error(`${info.file.name} 文件上传失败！`);
      return;
    }
    docFileUrl.value = info.file.response.data;
    form.documentUrl = docFileUrl.value;
    message.success(`${info.file.name} 文件上传成功！`);
  } else if (info.file.status === "error") {
    message.error(`${info.file.name} 文件上传失败！`);
  }
};

/**
 * 加载单类数据
 * @param params
 */
const loadData = (params: any) => {
  initLoading.value = false;
  const { type = "post" } = params;
  if (!type) {
    message.error("类别为空");
    return;
  }
  const query = {
    ...params,
    searchText: params.text,
  };
  myAxios.post("search/all", query).then((res: any) => {
    myDataList.value = res.dataMap;
    isGetData.value = true;
    //判断是否需要有获取更多的按钮
    console.log(query);
    console.log("判断是否需要有获取更多的按钮：" + query.type);
    initLoading.value = verifyLoading(query.type);
    console.log("我的打印：");
    console.log(myDataList);
  });
};

let searchParams = reactive(initSearchParams);

watchEffect(() => {
  searchParams = {
    ...initSearchParams,
    text: route.query.text,
    type: route.params.category,
  } as any;
  console.log("监听器");
  console.log(searchParams);
  isGetData.value = false;
  loadData(searchParams);
});

watch(refCurrent, () => {
  isGetData.value = false;
  loadData(searchParams);
});

const onSearch = (value: string) => {
  router.push({
    query: {
      ...searchParams,
      text: value,
    },
  });
};

const onTabChange = (key: string) => {
  router.push({
    path: `/${key}`,
    query: searchParams,
  });
};

const menus = ref([]);

const hasItem = (key: string) => {
  console.log("我的菜单是：");
  console.log(menus);
  return menus.value.find((item) => item.code === key) !== undefined;
};

//公告栏
const announcementMessage = ref("");
const showAnnouncement = ref(true);

onMounted(async () => {
  try {
    const response = await myAxios.get("/dataSourceSign/listAll");
    menus.value = response;
    console.log(menus);
    //获取公告
    const noticeRes = await myAxios.get("/noticeBoard/getContentForFeign");
    announcementMessage.value = noticeRes.content;
    console.log(announcementMessage);
  } catch (error) {
    console.error(error);
  }
  setTimeout(() => {
    showAnnouncement.value = false;
  }, 20000); // 设置为20秒
});
</script>

<style scoped>
.isGetData {
  text-align: center;
  background: rgba(0, 0, 0, 0.05);
  border-radius: 4px;
  margin-bottom: 20px;
  padding: 30px 50px;
  margin: 20px 0;
}
.announcement {
  height: 40px;
  width: 100%;
  line-height: 40px;
  overflow: hidden;
  background-color: #f7f5f5;
  padding: 0 20px;
}

.scrolling-text {
  animation: scrollText 10s linear infinite;
}

@keyframes scrollText {
  0% {
    transform: translateX(-100%);
  }
  100% {
    transform: translateX(100%);
  }
}
</style>
